import { IApi } from '@umijs/types';
import { AuthResultModal, DefaultConfigModal } from './modal';
import paths from './paths';
import fs from 'fs';
import { join } from 'path';
const filesPaths = [
  {
    path: './fns/sourceDataProvider.ts.tpl',
    outPath: paths.sourceDataProvider,
  },
  {
    path: './fns/sourceDataProvider.ts.tpl',
    outPath: paths.sourceDataProvider,
  },
  {
    path: './fns/authCheck.ts.tpl',
    outPath: paths.authCheck,
  },
  {
    path: './hooks/authCheckHooks.ts.tpl',
    outPath: paths.authCheckHooks,
  },
  {
    path: './fns/authProvider.ts.tpl',
    outPath: paths.authProvider,
  },
  {
    path: './components/AuthContext.tsx.tpl',
    outPath: paths.authContext,
  },
  {
    path: './components/CheckAuthComponent.tsx.tpl',
    outPath: paths.checkAuthComponent,
  },
  {
    path: './components/SettingAuthContext.tsx.tpl',
    outPath: paths.settingAuthContext,
  },
  {
    path: './modal.d.ts',
    outPath: paths.modal,
  },
  {
    path: './components/index.less',
    outPath: paths.styles,
  },
  {
    path: './utils/check.ts.tpl',
    outPath: paths.utilCheck,
  },
];
export default (api: IApi, authData: AuthResultModal) => {
  const config = api.config.hwAuth as DefaultConfigModal;
  const { locals = {} } = config;
  const { defaultLocal = 'cn' } = locals;
  const filesStrs = filesPaths.map(item => {
    const { path, outPath } = item;
    const relPath = join(__dirname, path);
    const content = fs.readFileSync(relPath).toString();
    return {
      content,
      outPath,
    };
  });
  // @ts-ignore
  const authStr = JSON.stringify(authData, '', '\t');
  const sourceData = {
    localKey: defaultLocal,
    appKey: authData.appKey,
    routes: authData.routes,
  }; //默认国际化key
  // @ts-ignore
  const sourceDataStr = JSON.stringify(sourceData, '', '\t');
  filesStrs.push(
    {
      content: authStr,
      outPath: paths.authJson,
    },
    {
      content: `export const sourceData=${sourceDataStr}`,
      outPath: paths.sourceDataFile,
    },
  );
  filesStrs.forEach(item => {
    const { content, outPath } = item;
    api.writeTmpFile({
      path: outPath,
      content,
    });
  });
};
